using System.Collections.Generic;
using PEMath;
using PEPhysx;
using UnityEngine;

/****************************************************
// 功能：主要逻辑单位 移动碰撞处理
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/28 16:31:15
*****************************************************/

public partial class MainLogicUnit
{
    
    // UI 输入方向
    public PEVector3 InputDir { private set; get; }

    // 当前战斗单位物理碰撞器
    public PECylinderCollider collider;
    // 所有环境碰撞体
    private List<PEColliderBase> envColliderList;
    
    // 临时存储UI输入方向，以便于施放技能再恢复方向输入
    private PEVector3 UIInputDir;

    /// <summary>
    /// 初始化移动
    /// 
    /// </summary>
    public void InitMove()
    {
        LogicPos = unitData.bornPos;
        moveSpeedBase = unitData.unitConfig.moveSpeed;
        LogicMoveSpeed = unitData.unitConfig.moveSpeed;
        envColliderList = BattleController.Instance.GetEnvColliders();
        collider = new PECylinderCollider(unitData.unitConfig.colliderConfig)
        {
            mPos = LogicPos
        };
    }
    
    /// <summary>
    /// 驱动移动碰撞
    /// </summary>
    public void TickMove()
    {
        PEVector3 moveDir = InputDir;
        collider.mPos += moveDir * LogicMoveSpeed * (PEInt) Constants.CLIENT_LOGIC_FRAME_DELTA_SEND;
        
        PEVector3 adj = PEVector3.zero;
        collider.CalcCollidersInteraction(envColliderList, ref moveDir, ref adj);
        if (LogicDir != moveDir)
        {
            LogicDir = moveDir;
        }

        if (LogicDir != PEVector3.zero)
        {
            LogicPos = collider.mPos + adj;
        }
        

        collider.mPos = LogicPos;
        //Debug.Log($"{unitName} pos： {collider.mPos.ConvertViewVector3()}");
    }

    /// <summary>
    /// 反初始化移动碰撞
    /// </summary>
    public void UninitMove()
    {
        
    }

    /// <summary>
    /// 模拟输入方向
    /// </summary>
    /// <param name="dir"></param>
    public void InputFakeMoveKey(PEVector3 dir)
    {
        InputDir = dir;
    }

    public void InputMoveKey(PEVector3 dir)
    {
        UIInputDir = dir;
        if (!IsSkillSpelling() && !IsStunned() && !IsKnockup())
        {
            InputDir = dir;
            //Debug.Log($"InputDir：{dir.ConvertViewVector3()}");
        }
    }

    /// <summary>
    /// 恢复UI输入
    /// </summary>
    public void RecoverUiInput()
    {
        if(InputDir != UIInputDir) {
            InputDir = UIInputDir;
        }
    }
    
    /// <summary>
    /// 是否移动
    /// 未被眩晕/击飞
    /// 未在其他技能施法前摇阶段
    /// </summary>
    /// <returns></returns>
    public bool CancelMove()
    {
        return !IsStunned() && !IsKnockup() && !IsSkillSpelling();
    }
}
